﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OracleDbTool;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System.IO;
using System.Collections.Specialized;
using MyConfigFile;

namespace hkjc
{
    public partial class FormHK : Form
    {
        string m_racedate;
        string m_venue;
        string m_raceno;
        int m_racecount;

        NameValueCollection m_sqls = new NameValueCollection();
        

        const int TOP_WIN_COUNT = 10;

        public FormHK()
        {
            InitializeComponent();

        }

        private void FormHK_Load(object sender, EventArgs e)
        {
            //查询数据库中的比赛列表
            cbRaceDate.DataSource = OrclFunc.QueryBySqlLocal(@"select racedate||'  '||venue raceinfo,max(racedate) racedate,max(venue) venue,count(*) 
                                        racecount from t_raceinfo t group by racedate||'  '||venue").Tables[0];
            cbRaceDate.SelectedIndex = 0;

            cbStatTime.SelectedIndex = 0;

            m_sqls = SimpleConfigFile.GetAllConfigs("sqls.cfg", "[@@", "@@]");
        }

        //refresh 10*10
        void RefreshTopWinOdds(int racecount)
        {
            int i;
            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            dgvTopWin.Rows.Clear();
            panel1.Height = dgvTopWin.ColumnHeadersHeight + dgvTopWin.RowTemplate.Height * racecount + 48;
            dgvTopWin.Height = panel1.Height - 45;
            Invalidate();
            Application.DoEvents();

            //增加三行
            DataSet ds;
            for (i = 1; i <= racecount; i++)
            {
                dgvTopWin.Rows.Add(i.ToString(), "", "", "", "", "", "", "", "", "", "");

                ds = GetTopWinOdds(m_racedate, m_venue, i.ToString(), endtime);

                if (ds != null)
                    for (int j = 1; j <= TOP_WIN_COUNT;j++)
                        if (j <= ds.Tables[0].Rows.Count)
                        {
                            dgvTopWin.Rows[i-1].Cells[j].Value = ds.Tables[0].Rows[j-1]["description"].ToString();
                            dgvTopWin.Rows[i-1].Cells[j].Tag = ds.Tables[0].Rows[j-1]["horseno"].ToString();
                        }
                ds = null;
            }

            //更4新racecount*10表格        


            /*int r1, r2, r3;
            r1 = int.Parse(m_raceno) - 1;
            r1 = (r1 > 0) ? r1 : 1;

            r2 = int.Parse(m_raceno);
            r2 = (r1 == 1) ? 2 : r2;

            r3 = r2 + 1;
            if (r3 > racecount && racecount >= 3)
            {
                r3 = racecount;
                r2 = racecount - 1;
                r1 = racecount - 2;
            }
            
            DataSet ds1 = null, ds2 = null, ds3 = null;

            List<string> ls = new List<string> { };
            if (r1 > 0)
            {
                ds1 = GetTopWinOdds(m_racedate, m_venue, r1.ToString(), endtime);
                dgvTopWin.Rows[0].Cells[0].Value = r1.ToString();
            }
            ds2 = GetTopWinOdds(m_racedate, m_venue, m_raceno, endtime);
            dgvTopWin.Rows[1].Cells[0].Value = r2.ToString();
            if (r3 <= racecount)
            {
                ds3 = GetTopWinOdds(m_racedate, m_venue, r3.ToString(), endtime);
                dgvTopWin.Rows[2].Cells[0].Value = r3.ToString();
            }


            for (i = 1; i <= TOP_WIN_COUNT; i++)
            {
                if (ds1 != null)
                    if (i <= ds1.Tables[0].Rows.Count)
                    {
                        dgvTopWin.Rows[0].Cells[i].Value = ds1.Tables[0].Rows[i]["description"].ToString();
                        dgvTopWin.Rows[0].Cells[i].Tag = ds1.Tables[0].Rows[i]["horseno"].ToString();
                    }
                if (ds2 != null)
                    if (i <= ds2.Tables[0].Rows.Count)
                    {
                        dgvTopWin.Rows[1].Cells[i].Value = ds2.Tables[0].Rows[i]["description"].ToString();
                        dgvTopWin.Rows[1].Cells[i].Tag = ds2.Tables[0].Rows[i]["horseno"].ToString();
                    }
                if (ds3 != null)
                    if (i <= ds3.Tables[0].Rows.Count)
                    {
                        dgvTopWin.Rows[2].Cells[i].Value = ds3.Tables[0].Rows[i]["description"].ToString();
                        dgvTopWin.Rows[2].Cells[i].Tag = ds3.Tables[0].Rows[i]["horseno"].ToString();
                    }
            }
            ds1 = null;
            ds2 = null;
            ds3 = null;*/
        }

        //fetch all data for the raceno
        private void RaceNoData(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(m_racedate) || string.IsNullOrEmpty(m_racedate) || string.IsNullOrEmpty(m_racedate))
            {
                MessageBox.Show("比赛日、场地或场次信息未填完整");
                return;
            }
                                   
            //RefreshTopWinOdds(m_racecount);

            //get race info
            /*string sql = m_sqls.Get("GetRaceInfo");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno);
            lblRaceInfo.Text = OrclFunc.ExecuteScalarStrLocal(sql);*/

            //get six lowest win-odds for the current race

            //switch to ALL table
            tabControl1.SelectedIndex = 5;
            //update time tag 
            lbWinRefreshTime.Text = DateTime.Now.ToShortTimeString();
            //refresh win odds table
            string sql = m_sqls.Get("GetWinOddsTable");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno);
            dgvOddsTableWin.DataSource = OrclFunc.QueryBySqlLocal(sql).Tables[0];

            //refresh dbl 
            button7_Click(null, null);
            //refresh pla 
            button2_Click(null, null);

            //all c 
            RefreshAllC();
            lbAllFreshTime.Text = DateTime.Now.ToShortTimeString();
        }

        void RefreshAllC()
        {
            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            //查询各彩池的最新批次数据
            string max_wp_batch = OrclFunc.ExecuteScalarStrLocal(string.Format(m_sqls.Get("all_max_wp_batch"), m_racedate, m_venue, m_raceno, starttime, endtime));
            string max_qpl_batch = OrclFunc.ExecuteScalarStrLocal(string.Format(m_sqls.Get("all_max_qpl_batch"), m_racedate, m_venue, m_raceno, starttime, endtime));
            string max_dbl_batch = OrclFunc.ExecuteScalarStrLocal(string.Format(m_sqls.Get("all_max_dbl_batch"), m_racedate, m_venue, m_raceno, starttime, endtime));

            string raceno_1 = (int.Parse(m_raceno) - 1).ToString();
            string max_dbl_batch_1 = OrclFunc.ExecuteScalarStrLocal(string.Format(m_sqls.Get("all_max_dbl_batch"), m_racedate, m_venue,
                    raceno_1, starttime, endtime));
            dgvAll.DataSource = OrclFunc.QueryBySqlLocal(string.Format(m_sqls.Get("all_c12"),
                    m_racedate, m_venue, m_raceno,
                    max_wp_batch, max_qpl_batch, max_dbl_batch, max_dbl_batch_1, raceno_1)).Tables[0];
        }

        private void dgvOddsTableWin_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            DataGridView dgvOddsTable = sender as DataGridView;
            foreach (DataGridViewColumn dgvc in dgvOddsTable.Columns)
            {
                dgvc.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
        }

        #region Show Odds history and chart
        //show win odds history and chart
        private void 显示历史赔率数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string horseno = "1";

            if (tabControl1.SelectedTab.Text == "独赢")
            {
                if (dgvOddsTableWin.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvOddsTableWin.SelectedRows[0].Cells["HorseNO"].Value);
            }
            else if (tabControl1.SelectedTab.Text == "All")
            {
                if (dgvAll.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvAll.SelectedRows[0].Cells["HORSENO"].Value);
            }

            //如果当前page是组合显示的page，则增加page
            if (tabControlPages.SelectedTab.Tag != null)
                AddViewPage(0, 0);

            AddWinOddsView(horseno);
        }

        private void AddWinOddsView(string horseno)
        {
            string caption = "R【" + m_raceno + "】H【" + horseno + "】" + GetHorseName(horseno);

            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            string sql = m_sqls.Get("GetWinOddsHistory");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno, horseno, starttime, endtime);

            FormTab fc = new FormTab(caption, sql, "WIN_Y+", "Win", "WIN_Y", "", "", "");
            fc.TopLevel = false;
            fc.Dock = DockStyle.None;

            AddViewWindow(fc);
            fc.Show();
        }

        private void 显示热门独赢赔率数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //AddViewPage(2, 3);
            int horsecount = HorseCount(m_raceno);
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);

            for (int i = 1; i <= horsecount; i++)
                AddWinOddsView(i.ToString());
            //for (int i = 0; i < 6; i++)
            //    AddWinOddsView(Convert.ToString(m_lstLinkLabels[0, i].Tag));
            SortWindows();
        }
        //show pla odds history and chart
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (dgvOddsTablePla.SelectedRows.Count <= 0)
                return;
            string horseno = Convert.ToString(dgvOddsTablePla.SelectedRows[0].Cells["HorseNo"].Value);

            //如果当前page是组合显示的page，则增加page
            if (tabControlPages.SelectedTab.Tag != null)
                AddViewPage(0, 0);

            AddPlaOddsView(horseno);
        }

        string GetHorseName(string horseno, string raceno2 = "")
        {
            string horsename = string.Empty;
            if (string.IsNullOrEmpty(horseno))
                return horsename;

            string sql = @"select horsename from t_racehorses where racedate='{0}' and 
                             venue='{1}' and raceno='{2}' and horseno='{3}'";
            try
            {
                if (string.IsNullOrEmpty(raceno2))
                    horsename = OrclFunc.ExecuteScalarStrLocal(string.Format(sql, m_racedate, m_venue, m_raceno, horseno));
                else
                    horsename = OrclFunc.ExecuteScalarStrLocal(string.Format(sql, m_racedate, m_venue, raceno2, horseno));

            }
            catch (Exception )
            {

            }
            return horsename;
        }

        private void AddPlaOddsView(string horseno)
        {
            string caption = "R【" + m_raceno + "】H【" + horseno + "】" + GetHorseName(horseno);

            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            string sql = m_sqls.Get("GetPlaOddsHistory");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno, horseno, starttime, endtime);

            FormTab fc = new FormTab(caption, sql, "Pla_Y+", "Pla", "Pla_Y", "", "", "");
            fc.TopLevel = false;
            fc.Dock = DockStyle.None;
            AddViewWindow(fc);
            fc.Show();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            //AddViewPage(2, 3);

            int horsecount = HorseCount(m_raceno);
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);

            for (int i = 1; i <= horsecount; i++)
                AddPlaOddsView(i.ToString());
            //for (int i = 0; i < 6; i++)
            //    AddPlaOddsView(Convert.ToString(m_lstLinkLabels[0, i].Tag));
            SortWindows();
        }
        //show qin odds history and chart
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (dgvOddsTableQin.SelectedRows.Count <= 0)
                return;
            string horseno1 = Convert.ToString(dgvOddsTableQin.SelectedRows[0].Cells["HorseNo1"].Value);
            string horseno2 = Convert.ToString(dgvOddsTableQin.SelectedRows[0].Cells["HorseNo2"].Value);

            //如果当前page是组合显示的page，则增加page
            if (tabControlPages.SelectedTab.Tag != null)
                AddViewPage(0, 0);

            AddQinOddsView(horseno1, horseno2);
        }
        private void AddQinOddsView(string horseno1, string horseno2)
        {
            string caption = "R【" + m_raceno + "】H【" + horseno1 + "," + horseno2 + "】" + GetHorseName(horseno1) + "+" + GetHorseName(horseno2);

            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            string sql = m_sqls.Get("GetQinOddsHistory");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno, horseno1, horseno2, starttime, endtime);

            FormTab fc = new FormTab(caption, sql, "Qin_Y+", "Qin", "Qin_Y", "Win1", "Win2", "", "");
            fc.TopLevel = false;
            fc.Dock = DockStyle.None;
            AddViewWindow(fc);
            fc.Show();
        }
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            if (dgvOddsTableQin.SelectedRows.Count <= 0)
                return;
            //AddViewPage(2, 3);
            string horseno1 = Convert.ToString(dgvOddsTableQin.SelectedRows[0].Cells["HorseNo1"].Value);


            int horsecount = HorseCount(m_raceno);
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);

            for (int i = 1; i <= horsecount; i++)
                if (i.ToString() != horseno1)
                    AddQinOddsView(i.ToString(), horseno1);

            //for (int i = 0; i < 6; i++)
            //    if (Convert.ToString(m_lstLinkLabels[0, i].Tag) != horseno1)
            //        AddQinOddsView(Convert.ToString(m_lstLinkLabels[0, i].Tag),horseno1);

            SortWindows();
        }
        //show qpl odds history and chart
        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            if (dgvOddsTableQpl.SelectedRows.Count <= 0)
                return;
            //如果当前page是组合显示的page，则增加page
            if (tabControlPages.SelectedTab.Tag != null)
                AddViewPage(0, 0);

            string horseno1 = Convert.ToString(dgvOddsTableQpl.SelectedRows[0].Cells["HorseNo1"].Value);
            string horseno2 = Convert.ToString(dgvOddsTableQpl.SelectedRows[0].Cells["HorseNo2"].Value);
            AddQplOddsView(horseno1, horseno2);
        }
        private void AddQplOddsView(string horseno1, string horseno2)
        {
            string caption = "R【" + m_raceno + "】H【" + horseno1 + "," + horseno2 + "】" + GetHorseName(horseno1) + "+" + GetHorseName(horseno2);

            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            string sql = m_sqls.Get("GetQplOddsHistory");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno, horseno1, horseno2, starttime, endtime);

            File.WriteAllText(Application.StartupPath + "\\sql.txt", sql);

            FormTab fc = new FormTab(caption, sql, "Qpl_Y+", "QPL", "Qpl_Y", "Win1", "Win2", "", "");
            fc.TopLevel = false;
            fc.Anchor = System.Windows.Forms.AnchorStyles.Left & AnchorStyles.Top;
            fc.Dock = DockStyle.None;
            AddViewWindow(fc);
            fc.Show();
        }
        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            if (dgvOddsTableQpl.SelectedRows.Count <= 0)
                return;
            //AddViewPage(2, 3);
            string horseno1 = Convert.ToString(dgvOddsTableQpl.SelectedRows[0].Cells["HorseNo1"].Value);

            int horsecount = HorseCount(m_raceno);
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);

            for (int i = 1; i <= horsecount; i++)
                if (i.ToString() != horseno1)
                    AddQplOddsView(i.ToString(), horseno1);

            // for (int i = 0; i < 6; i++)
            //     if (Convert.ToString(m_lstLinkLabels[0, i].Tag) != horseno1)
            //         AddQinOddsView(Convert.ToString(m_lstLinkLabels[0, i].Tag), horseno1);

            SortWindows();
        }
        //show dbl odds history and chart
        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            if (dgvOddsTableDbl.SelectedRows.Count <= 0)
                return;

            //如果当前page是组合显示的page，则增加page
            if (tabControlPages.SelectedTab.Tag != null)
                AddViewPage(0, 0);

            string horseno1 = Convert.ToString(dgvOddsTableDbl.SelectedRows[0].Cells["HorseNo1"].Value);
            string horseno2 = Convert.ToString(dgvOddsTableDbl.SelectedRows[0].Cells["HorseNo2"].Value);
            AddDblOddsView(m_raceno,horseno1, horseno2);
        }
        private void AddDblOddsView(string raceno,string horseno1, string horseno2)
        {
            if (m_racecount == int.Parse(raceno))
            {
                MessageBox.Show("尾场没有孖宝赔率");
                return;
            }
            string caption = "R【" + raceno + "】H【" + horseno1 + "】" + " @@ R【" + (int.Parse(raceno) + 1).ToString() + "】H【" + horseno2 + "】" + GetHorseName(horseno1, raceno) + "+" + GetHorseName(horseno2, (int.Parse(raceno) + 1).ToString());

            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            string sql = m_sqls.Get("GetDblOddsHistory");
            sql = string.Format(sql, m_racedate, m_venue, raceno, horseno1, horseno2, starttime, endtime);

            FormTab fc = new FormTab(caption, sql, "Dbl_Y+", "Dbl", "Dbl_Y", "Win1", "Win2", "Win*", "");
            fc.TopLevel = false;
            fc.Dock = DockStyle.None;
            AddViewWindow(fc);
            fc.Show();
        }
        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            if (dgvOddsTableDbl.SelectedRows.Count <= 0)
                return;
            //AddViewPage(2, 3);
            string horseno1 = Convert.ToString(dgvOddsTableDbl.SelectedRows[0].Cells["HorseNo1"].Value);

            int horsecount = HorseCount((int.Parse(m_raceno) + 1).ToString());
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);

            for (int i = 1; i <= horsecount; i++)
                AddDblOddsView(m_raceno,horseno1, i.ToString());

            //for (int j = 0; j < 6; j++)
            //    AddDblOddsView(horseno1, Convert.ToString(m_lstLinkLabels[1, j].Tag));

            SortWindows();
        }
        #endregion

        #region layout of page setting
        private string NewCaption()
        {
            string caption = "页面";
            int i = 0; int j = 1;
            while (true)
            {
                i = 0;
                while (i < tabControlPages.TabPages.Count)
                {
                    if (tabControlPages.TabPages[i].Text == "页面" + j.ToString())
                        break;
                    i++;
                }
                if (i < tabControlPages.TabPages.Count) //already exists 
                    j++;
                else
                {
                    caption = "页面" + j.ToString();
                    break;
                }
            }

            return caption;
        }

        private void 增加视图页面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string caption = "Page";
            int i = 0; int j = 1;
            while (true)
            {
                i = 0;
                while (i < tabControlPages.TabPages.Count)
                {
                    if (tabControlPages.TabPages[i].Text == "Page" + j.ToString())
                        break;
                    i++;
                }
                if (i < tabControlPages.TabPages.Count) //already exists 
                    j++;
                else
                {
                    caption = "Page" + j.ToString();
                    break;
                }
            }
            TabPage tp = new TabPage(caption);
            tp.BackColor = SystemColors.AppWorkspace;
            tabControlPages.TabPages.Add(tp);
        }

        private void 删除试图页面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tabControlPages.SelectedTab != null && tabControlPages.TabPages.Count > 1)
                tabControlPages.TabPages.Remove(tabControlPages.SelectedTab);
        }

        private void AddViewPage(int rowcount, int columncount)
        {
            TabPage tp = new TabPage(NewCaption());
            tp.BackColor = SystemColors.AppWorkspace;


            tabControlPages.TabPages.Add(tp);
            tabControlPages.SelectedTab = tp;

            if (rowcount * columncount > 0)
            {
                FormPos fp = new FormPos();
                fp.rowsize = rowcount;
                fp.colsize = columncount;
                tp.Tag = fp;
            }
        }

        // layout of 1 row * 2 columns
        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            AddViewPage(1, 2);
        }
        private void 布局ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddViewPage(2, 2);
        }

        private void 布局ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            AddViewPage(1, 3);
        }

        private void 布局ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            AddViewPage(2, 3);
        }

        private void 任意放置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddViewPage(0, 0);
        }
        private void AddViewWindow(FormTab ft)
        {
            int i = tabControlPages.SelectedTab.Controls.Count;

            if (tabControlPages.SelectedTab.Tag != null)
            {
                FormPos fp = tabControlPages.SelectedTab.Tag as FormPos;
                int cellheight = tabControlPages.SelectedTab.Height / fp.rowsize;
                int cellwidth = tabControlPages.SelectedTab.Width / fp.colsize;

                ft.Top = (fp.index / fp.colsize) * cellheight;
                ft.Left = (fp.index % fp.colsize) * cellwidth;

                ft.Width = cellwidth;
                ft.Height = cellheight;
                ft.m_index = fp.index;
                tabControlPages.SelectedTab.Controls.Add(ft);
                fp.index++;
            }
            else if (i > 0)
            {
                ft.Left = tabControlPages.SelectedTab.Controls[0].Left + 20;
                ft.Top = tabControlPages.SelectedTab.Controls[0].Top + 20;
                tabControlPages.SelectedTab.Controls.Add(ft);
                ft.BringToFront();
            }
            else
            {
                tabControlPages.SelectedTab.Controls.Add(ft);
                ft.BringToFront();
            }

        }
        #endregion

        private void dgvOddsTableWin_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            if (dgv.Columns.Count == 0)
                return;
            string fn = dgv.Columns[e.ColumnIndex].Name.ToUpper();
            if (fn.Contains("HORSENO"))
            {
                e.CellStyle.Font = new Font(dgv.Font, FontStyle.Bold);
                e.CellStyle.ForeColor = Color.DarkBlue;
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

                //双号背景色
                if (Convert.ToInt32(e.Value) % 2 == 0)
                {
                    e.CellStyle.BackColor = Color.LightYellow;
                }
            }
            else if (fn == "WIN"
                || fn == "PLA"
                || fn == "QIN"
                || fn == "QPL"
                || fn == "DBL"
                || fn == "WIN1"
                || fn == "WIN2"
                //|| fn == "PLA1"
                //|| fn == "PLA2"
                )
            {
                e.CellStyle.Font = new Font(dgv.Font, FontStyle.Bold);
                e.CellStyle.ForeColor = Color.Red;
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            }
            //if ((fn.ToUpper() != "JOCKEY") && (fn.Contains("Y")
            //    || fn.Contains("INV")))
            else if ((fn.ToUpper() != "JOCKEY") && (fn.ToUpper() != "HORSENAME") && (fn.ToUpper() != "TRAINER"))
            {
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                e.CellStyle.Format = "N2";
            }

            float f = 0.0f;
            if (float.TryParse(e.Value.ToString(),out f))
                if (f < 0)
                {
                    e.CellStyle.BackColor = Color.LightBlue;
                }
        }

        void GetUpdTimeCondition(out string starttime, out string endtime)
        {
            starttime = string.Empty;
            endtime = string.Empty;

            DateTime dtEnd = DateTime.Now;
            if (!rbNow.Checked) //from specified time backward
                dtEnd = DateTime.ParseExact(dtChartEndTime.Text, "yyyy-MM-dd HH:mm", null);

            DateTime dtStart = dtEnd;
            switch (cbStatTime.Text)
            {
                case "15分钟":
                    dtStart = dtEnd.AddMinutes(-15);
                    break;
                case "30分钟":
                    dtStart = dtEnd.AddMinutes(-30);
                    break;
                case "1小时":
                    dtStart = dtEnd.AddHours(-1);
                    break;
                case "2小时":
                    dtStart = dtEnd.AddHours(-2);
                    break;
                case "4小时":
                    dtStart = dtEnd.AddHours(-4);
                    break;
                case "8小时":
                    dtStart = dtEnd.AddHours(-8);
                    break;
                case "16小时":
                    dtStart = dtEnd.AddHours(-16);
                    break;
                case "24小时":
                    dtStart = dtEnd.AddHours(-24);
                    break;
                case "全部":
                    dtStart = DateTime.ParseExact("20000101", "yyyyMMdd", null);
                    break;
            }

            starttime = dtStart.ToString("yyyy-MM-dd HH:mm:ss");
            endtime = dtEnd.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //update time tag 
            lbWinRefreshTime.Text = DateTime.Now.ToShortTimeString();

            //refresh win odds table
            string sql = m_sqls.Get("GetWinOddsTable");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno);
            dgvOddsTableWin.DataSource = OrclFunc.QueryBySqlLocal(sql).Tables[0];
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //update time tag 
            lbPlaRefreshTime.Text = DateTime.Now.ToShortTimeString();

            //refresh pla odds table
            string sql = m_sqls.Get("GetPlaOddsTable");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno);
            dgvOddsTablePla.DataSource = OrclFunc.QueryBySqlLocal(sql).Tables[0];
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //update time tag 
            lbQinRefreshTime.Text = DateTime.Now.ToShortTimeString();

            //refresh qin odds table
            string sql = m_sqls.Get("GetQinOddsTable");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno);
            dgvOddsTableQin.DataSource = OrclFunc.QueryBySqlLocal(sql).Tables[0];
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //update time tag 
            lbQplRefreshTime.Text = DateTime.Now.ToShortTimeString();

            //refresh qpl odds table
            string sql = m_sqls.Get("GetQplOddsTable");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno);
            dgvOddsTableQpl.DataSource = OrclFunc.QueryBySqlLocal(sql).Tables[0];
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //update time tag 
            lbDblRefreshTime.Text = DateTime.Now.ToShortTimeString();

            //refresh dbl odds table
            string sql = m_sqls.Get("GetDblOddsTable");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno);
            dgvOddsTableDbl.DataSource = OrclFunc.QueryBySqlLocal(sql).Tables[0];
        }

        int HorseCount(string raceno)
        {
            return OrclFunc.ExecuteScalarIntLocal(string.Format("select count(*) from T_RACEHORSES t where t.racedate='{0}' and raceno='{1}'", m_racedate, raceno));
        }

        string MaxBatchNoQinQpl(string raceno)
        {
            return OrclFunc.ExecuteScalarStrLocal(string.Format(@"select max(batchno) from T_QUINELLAPLACE_ODDS  where  racedate = '{0}' and venue = '{1}' and raceno = '{2}'",
                        m_racedate, m_venue, raceno));
        }
        string MaxBatchNoWinPla(string raceno)
        {
            return OrclFunc.ExecuteScalarStrLocal(string.Format(@"select max(batchno) from T_WINPLACE_ODDS  where  racedate = '{0}' and venue = '{1}' and raceno = '{2}'",
                        m_racedate, m_venue, raceno));
        }
        string MaxBatchNoDbl(string raceno)
        {
            return OrclFunc.ExecuteScalarStrLocal(string.Format(@"select max(batchno) from T_DOUBLE_ODDS  where  racedate = '{0}' and venue = '{1}' and raceno1 = '{2}'",
                        m_racedate, m_venue, raceno));
        }

        //所有连赢组合
        private void 显示该马号的所有位置组合ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string horseno = "1";

            if (tabControl1.SelectedTab.Text == "独赢")
            {
                if (dgvOddsTableWin.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvOddsTableWin.SelectedRows[0].Cells["HorseNO"].Value);
            }
            else if (tabControl1.SelectedTab.Text == "All")
            {
                if (dgvAll.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvAll.SelectedRows[0].Cells["HORSENO"].Value);
            }

            //4*3  3*3  2*3
            int horsecount = HorseCount(m_raceno);
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);


            //按赔率由低至高添加视图
            string sql = @"select t.horseno1,t.horseno2 from t_quinellaplace_odds t
                        where t.racedate='{0}'
                        and raceno='{1}'
                        and (t.horseno1 = '{2}' or horseno2 = '{2}')
                        and batchno='{3}'
                        order by t.q_odds asc";
            DataTable dt = OrclFunc.QueryBySqlLocal(string.Format(sql, m_racedate, m_raceno, horseno, MaxBatchNoQinQpl(m_raceno))).Tables[0];

            foreach (DataRow dr in dt.Rows)
                AddQinOddsView(dr["horseno1"].ToString(), dr["horseno2"].ToString());

            SortWindows();
        }

        private void 显示该马号的所有连赢组合ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string horseno = "1";

            if (tabControl1.SelectedTab.Text == "独赢")
            {
                if (dgvOddsTableWin.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvOddsTableWin.SelectedRows[0].Cells["HorseNO"].Value);
            }
            else if (tabControl1.SelectedTab.Text == "All")
            {
                if (dgvAll.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvAll.SelectedRows[0].Cells["HORSENO"].Value);
            }

            //4*3  3*3  2*3
            int horsecount = HorseCount(m_raceno);
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);


            //按赔率由低至高添加视图
            string sql = @"select t.horseno1,t.horseno2 from t_quinellaplace_odds t
                        where t.racedate='{0}'
                        and raceno='{1}'
                        and (t.horseno1 = '{2}' or horseno2 = '{2}')
                        and batchno='{3}'
                        order by t.qp_odds asc";
            DataTable dt = OrclFunc.QueryBySqlLocal(string.Format(sql, m_racedate, m_raceno, horseno, MaxBatchNoQinQpl(m_raceno))).Tables[0];


            foreach (DataRow dr in dt.Rows)
                AddQplOddsView(dr["horseno1"].ToString(), dr["horseno2"].ToString());

            SortWindows();
        }

        private void 显示该马号的所有孖宝组合ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string horseno = "1";

            if (tabControl1.SelectedTab.Text == "独赢")
            {
                if (dgvOddsTableWin.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvOddsTableWin.SelectedRows[0].Cells["HorseNO"].Value);
            }
            else if (tabControl1.SelectedTab.Text == "All")
            {
                if (dgvAll.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvAll.SelectedRows[0].Cells["HORSENO"].Value);
            }

            //4*3  3*3  2*3
            int horsecount = HorseCount((int.Parse(m_raceno) + 1).ToString());
            if (horsecount > 4 * 3)
                AddViewPage(4, 4);
            else if (horsecount > 3 * 3)
                AddViewPage(3, 4);
            else if (horsecount > 2 * 3)
                AddViewPage(3, 3);
            else
                AddViewPage(2, 3);


            //按赔率由低至高添加视图
            string sql = @"select t.horseno1,t.horseno2 from t_double_odds t
                        where t.racedate='{0}'
                        and raceno1='{1}' and horseno1='{2}'                        
                        and batchno='{3}'
                        order by t.d_odds asc";
            DataTable dt = OrclFunc.QueryBySqlLocal(string.Format(sql, m_racedate, m_raceno, horseno, MaxBatchNoDbl(m_raceno))).Tables[0];


            foreach (DataRow dr in dt.Rows)
                AddDblOddsView(m_raceno,dr["horseno1"].ToString(), dr["horseno2"].ToString());

            SortWindows();
        }

        private void tabControlPages_SizeChanged(object sender, EventArgs e)
        {
            if (tabControlPages.SelectedTab == null)
                return;
            if (tabControlPages.SelectedTab.Tag != null)
            {
                FormPos fp = (FormPos)tabControlPages.SelectedTab.Tag;
                int cellheight = tabControlPages.SelectedTab.Height / fp.rowsize;
                int cellwidth = tabControlPages.SelectedTab.Width / fp.colsize;
                foreach (Control ctrl in tabControlPages.SelectedTab.Controls)
                {
                    FormTab ft = ctrl as FormTab;
                    ft.Top = (ft.m_index / fp.colsize) * cellheight;
                    ft.Left = (ft.m_index % fp.colsize) * cellwidth;

                    ft.Width = cellwidth;
                    ft.Height = cellheight;
                }
            }
        }

        private void cbRaceDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataRowView drv = (DataRowView)cbRaceDate.SelectedItem;
            //设置可选场次
            for (int i = 0; i < panel12.Controls.Count; i++)
            {
                Button btn = panel12.Controls[i] as Button;
                if (int.Parse(btn.Text) > int.Parse(drv["racecount"].ToString()))
                {
                    panel12.Controls[i].Enabled = false;
                    panel12.Controls[i].BackColor = Color.DimGray;
                }
                else
                {
                    panel12.Controls[i].Enabled = true;
                    panel12.Controls[i].BackColor = Color.SteelBlue;
                }
            }
            //
            m_racedate = drv["racedate"].ToString();
            m_venue = drv["venue"].ToString();

            m_racecount = OrclFunc.ExecuteScalarIntLocal("select max(raceno) from t_raceinfo where racedate='" + m_racedate + "'");

            RefreshTopWinOdds(m_racecount);
            lbTopWinFreshTime.Text = DateTime.Now.ToShortTimeString();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            m_raceno = (sender as Button).Text;
            (sender as Button).BackColor = Color.Red;
            RaceNoData(null, null);

            dgvTopWin.Invalidate();

            for (int i = 0; i < panel12.Controls.Count; i++)
            {
                Button btn = panel12.Controls[i] as Button;
                if (btn.Text != (sender as Button).Text)
                    btn.BackColor = Color.SteelBlue;
            }
        }

        //窗口排序
        private void SortWindows()
        {
            FormPos fp = new FormPos();
            if (tabControlPages.SelectedTab.Tag != null)
                fp = tabControlPages.SelectedTab.Tag as FormPos;
            else
                return;

            List<double> values = new List<double> { };
            //当前tabpage
            foreach (Control ctrl in tabControlPages.SelectedTab.Controls)
            {
                values.Add((ctrl as FormTab).sortvalue);
                (ctrl as FormTab).m_index = -1;
            }

            //排序
            double[] arr = values.ToArray();
            Array.Sort(arr);
            int cellheight = tabControlPages.SelectedTab.Height / fp.rowsize;
            int cellwidth = tabControlPages.SelectedTab.Width / fp.colsize;
            //显示
            for (int i = 0; i <= arr.GetUpperBound(0); i++)
            {
                foreach (Control ctrl in tabControlPages.SelectedTab.Controls)
                {
                    FormTab ft = (ctrl as FormTab);
                    if (ft.m_index == -1 && ft.sortvalue == arr[i])
                    {
                        //按位置i显示
                        ft.Top = (i / fp.colsize) * cellheight;
                        ft.Left = (i % fp.colsize) * cellwidth;

                        ft.Width = cellwidth;
                        ft.Height = cellheight;
                        ft.m_index = i;
                        break;
                    }
                }
            }
        }

        private void 删除所有视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int c = tabControlPages.TabPages.Count;
            for (int i = 1; i < c; i++)
                tabControlPages.TabPages.RemoveAt(1);
        }

        private void 显示热门独赢赔率数据6项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripMenuItem2_Click(null, null);
        }

        private void button20_Click(object sender, EventArgs e)
        {
            RefreshAllC();
            lbAllFreshTime.Text = DateTime.Now.ToShortTimeString();
        }

        private void dgvOddsTableWin_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var grid = sender as DataGridView;
            var rowIdx = (e.RowIndex + 1).ToString();

            var centerFormat = new StringFormat()
            {
                // right alignment might actually make more sense for numbers
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };

            var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
        }

        private void AddAllPercentView(string horseno)
        {
            string caption = "R【" + m_raceno + "】H【" + horseno + "】" + GetHorseName(horseno);

            string starttime;
            string endtime;
            GetUpdTimeCondition(out starttime, out endtime);

            string sql = m_sqls.Get("all_percents");
            sql = string.Format(sql, m_racedate, m_venue, m_raceno, horseno, (int.Parse(m_raceno) - 1).ToString(), starttime, endtime);

            //"win%","pla%","qin%","qpl%","dbl_2%","dbl_1%"
            FormTab fc = new FormTab(caption, sql, "", "win%", "pla%", "qin%", "qpl%", "dbl_2%", "batchtime", "dbl_1%");
            fc.TopLevel = false;
            fc.Dock = DockStyle.None;

            AddViewWindow(fc);
            fc.Show();
        }

        private void 显示该马号的ALL百分比ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string horseno = "1";

            if (tabControl1.SelectedTab.Text == "独赢")
            {
                if (dgvOddsTableWin.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvOddsTableWin.SelectedRows[0].Cells["HorseNO"].Value);
            }
            else if (tabControl1.SelectedTab.Text == "All")
            {
                if (dgvAll.SelectedRows.Count <= 0)
                    return;
                horseno = Convert.ToString(dgvAll.SelectedRows[0].Cells["HORSENO"].Value);
            }

            //如果当前page是组合显示的page，则增加page
            if (tabControlPages.SelectedTab.Tag != null)
                AddViewPage(0, 0);

            AddAllPercentView(horseno);
        }
        #region 取某一场的独赢赔率排行数据
        DataSet GetTopWinOdds(string racedate, string venue, string raceno, string endtime)
        {            
            OracleParameter op1 = new OracleParameter("i_racedate", OracleDbType.Varchar2, 20,racedate, ParameterDirection.Input);            
            OracleParameter op2 = new OracleParameter("i_venue", OracleDbType.Varchar2, 20,venue, ParameterDirection.Input);
            OracleParameter op3 = new OracleParameter("i_raceno", OracleDbType.Varchar2, 20,raceno, ParameterDirection.Input);
            OracleParameter op4 = new OracleParameter("i_endtime", OracleDbType.Varchar2, 20,endtime, ParameterDirection.Input);
            OracleParameter ret = new OracleParameter("o_result", OracleDbType.RefCursor, ParameterDirection.Output);

            DataSet ds = OrclFunc.StoredProcDSLocal(new Oracle.DataAccess.Client.OracleParameter[] { op1, op2, op3, op4, ret }, "GetTopWinOdds");

            return ds;
        }
        #endregion

        private void dgvTopWin_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvTopWin.Rows[e.RowIndex].Cells[e.ColumnIndex] == null)
                return;

            string horseno = dgvTopWin.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag.ToString();

            if (string.IsNullOrEmpty(horseno))
                return;

            int i;

            int firstRaceno;
            if (e.RowIndex - 1 >= 0) //上场、本场
            {
                AddViewPage(3, 4);
                firstRaceno = e.RowIndex;
                for (i = 1; i <= TOP_WIN_COUNT; i++)
                    if (!string.IsNullOrEmpty(dgvTopWin.Rows[e.RowIndex - 1].Cells[i].Value.ToString()))
                        AddDblOddsView(firstRaceno.ToString(), Convert.ToString(dgvTopWin.Rows[e.RowIndex - 1].Cells[i].Tag), horseno);

                SortWindows();
            }

            if (e.RowIndex+1 <= m_racecount - 1) //本场、下一场
            {
                AddViewPage(3, 4);
                firstRaceno = e.RowIndex + 1;
                for (i = 1; i <= TOP_WIN_COUNT && !string.IsNullOrEmpty(dgvTopWin.Rows[e.RowIndex + 1].Cells[0].Value.ToString()); i++)
                    if (!string.IsNullOrEmpty(dgvTopWin.Rows[e.RowIndex + 1].Cells[i].Value.ToString()))
                        AddDblOddsView(firstRaceno.ToString(), horseno, Convert.ToString(dgvTopWin.Rows[e.RowIndex + 1].Cells[i].Tag));

                SortWindows();
            }

            
        }

        private void dgvTopWin_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex % 2 == 0)
                e.CellStyle.BackColor = Color.FloralWhite;

            if (!string.IsNullOrEmpty(m_raceno))
                if (e.RowIndex == int.Parse(m_raceno) - 1)
                {
                    e.CellStyle.BackColor = Color.LightBlue;
                }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            RefreshTopWinOdds(m_racecount);
            lbTopWinFreshTime.Text = DateTime.Now.ToShortTimeString();
        }

        private void 显示所有马号的ALL百分比ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(m_raceno))
                return;

            //如果当前page是组合显示的page，则增加page
            //if (tabControlPages.SelectedTab.Tag != null)
                AddViewPage(4, 4);

            foreach (DataGridViewRow dgvr in dgvAll.Rows)
            {
                AddAllPercentView(dgvr.Cells["horseno"].Value.ToString());
            }
        }

        private void lbAllFreshTime_Click(object sender, EventArgs e)
        {

        }
    }

    public class FormPos
    {
        public int rowsize;
        public int colsize;
        public int index = 0;
    }
}
